package com.engine.ld.optimize;

import com.weaver.general.BaseBean;
import com.weaver.general.Util;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import weaver.conn.RecordSet;
import weaver.soa.workflow.request.RequestInfo;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/7/13
 */
public class CgxxNew {
    private static final BaseBean bb = new BaseBean();

    public String CgxxSelect(String requestid, RequestInfo requestInfo) throws ParserConfigurationException {
        bb.writeLog("进入CgxxSelect成功");
        String[] headField = {"LIFNR", "MATNR", "INFNR", "ESOKZ", "VERKF", "TELF1", "MEINS", "UMREN", "UMREZ", "URZLA", "ZFLAG",
                "LOEKZ", "EKORG", "APLFZ", "EKGRP", "NORBM", "MINBM", "UEBTO", "MWSKZ", "WEBRE", "NETPR", "WAERS", "PEINH",
                "BPRME", "KSCHL", "PRDAT", "BPUMN", "BPUMZ", "EINELOEKZ", "ZYXQBS", "ZJTBS", "DATAB", "DATBI", "KSTBM", "KONMS",
                "KBETR", "ZTJYW","ZCZTJ"};
        String[] itemField = {"LIFNR", "MATNR", "INFNR", "ZJTBS", "DATAB", "DATBI", "KSTBM", "KONMS", "KBETR"};

        String tableName = requestInfo.getRequestManager().getBillTableName();

        bb.writeLog("获得的表名："+tableName);
        Map<String, Object> headData = getData(headField, requestid, tableName);
        bb.writeLog("从数据库中查询的HEAD节点数据是：" + headData);
        Map<String, Object> itemData = getData(itemField, requestid, tableName);
        bb.writeLog("从数据库中查询的ITEM节点数据是：" + itemData);

        bb.writeLog("准备执行xml组装语句");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Element root = document.createElement("ROOT");
        document.appendChild(root);

        Element head = document.createElement("HEAD");
        for (String s : headField) {
            if ("EINELOEKZ".equals(s)) {
                appendChild(document, head, "LOEKZ1", headData.get(s).toString());
                bb.writeLog("LOEKZ1节点添加成功");
            } else {
                appendChild(document, head, s, headData.get(s).toString());
                bb.writeLog(s + "节点插入成功");
            }
        }
        //        根据业务标识为HRAD节点下的ZCZTJ节点赋值
//        if ("2".equals(headData.get("ZFLAG").toString())) {
//            appendChild(document, head, "ZCZTJ", "X");
//            bb.writeLog( "ZFLAG节点插入成功，它的值是X");
//        } else {
//            appendChild(document, head, "ZCZTJ", "");
//            bb.writeLog( "ZFLAG节点插入成功，它的值是空");
//        }
        root.appendChild(head);

//        ITEM
        Element item = document.createElement("ITEM");
        for (String s : itemField) {
            appendChild(document, item, s, itemData.get(s).toString());
            bb.writeLog("ITEM节点中"+s+"子节点添加成功");
        }
        root.appendChild(item);

        bb.writeLog("传给SAP的参数是：" + createXmlToString(document));

        return createXmlToString(document);
    }

    /**
     * @param fields    需要查询字段的String类型数组
     * @param requestid where条件
     *                  实现查询并将结果存储到Map集合中
     */
    private Map<String, Object> getData(String[] fields, String requestid, String tableName) {
        Map<String, Object> data = new HashMap<>();
        String mainsql = "select ";
        for (int i = 0; i < fields.length; i++) {
            if (i == fields.length - 1) {
                mainsql += fields[i] + " ";
            } else if ("ZJTBS".equals(fields[i])) {
                mainsql += "";
            } else {
                mainsql += fields[i] + ",";
            }
        }
        mainsql += "from " + tableName + " a where a.requestid=" + requestid;

        RecordSet rs = new RecordSet();
        rs.executeQuery(mainsql);
        while (rs.next()) {
            for (String field : fields) {
                data.put(field, Util.null2String(rs.getString(field)));
            }
        }
        return data;
    }

    /**
     * document对象中添加子项
     *
     * @param document ducument对象
     * @param parent   父元素
     * @param key      元素标签
     * @param value    元素content值
     */
    private static void appendChild(Document document, Element parent, String key, String value) {
        Element child = document.createElement(key);
        if (child != null) {
            child.setTextContent(value);
        }
        parent.appendChild(child);
    }

    /**
     * 生成xml字符串
     *
     * @param document Document树对象
     * @return 整个xml字符串
     */
    private static String createXmlToString(org.w3c.dom.Document document) {
        String xmlString = null;
        try {
            // 创建TransformerFactory工厂对象
            TransformerFactory transFactory = TransformerFactory.newInstance();
            // 通过工厂对象, 创建Transformer对象
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            //使Xml自动换行, 并自动缩进
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");  //中间的参数网址固定写法(这里还没搞懂)
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                          //是否设置缩进（indent: yes|no）
            // 创建DOMSource对象并将Document加载到其中
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 使用Transformer的transform()方法将DOM树转换成XML
            transformer.transform(domSource, new StreamResult(bos));
            xmlString = bos.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return xmlString;
    }
}
